const Activity = require('../model/activity.model')
const { Op } = require("sequelize")

class ActivityService {
    /**
     * 创建活动
     */
    async createActivity (actData) {
        // 插入数据
        try {
            const res = await Activity.create(actData)
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }

    /**
     * 按照act_id 删除一个活动
     */
    async deleteByActId (act_id) {
        try {
            const res = await Activity.destroy({ where: { act_id } })
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }

    /**
     * 按照默写字段查找活动表
     */
    async getActInfo ({ act_id, act_title, teacher_account, organizer_account, act_type, approval_status, score_approval_status, sign_type, time, offect = 0, limit = 100 }) {
        const whereOpt = {}
        // 短路运算 值存在就拷贝进whereOpt
        act_id && Object.assign(whereOpt, { act_id })
        act_title && Object.assign(whereOpt, { act_title })
        teacher_account && Object.assign(whereOpt, { teacher_account })
        organizer_account && Object.assign(whereOpt, { organizer_account })
        act_type && Object.assign(whereOpt, { act_type })
        approval_status && Object.assign(whereOpt, { approval_status })
        score_approval_status && Object.assign(whereOpt, { score_approval_status })
        sign_type && Object.assign(whereOpt, { sign_type })
        time && Object.assign(whereOpt, {
            end_time: {
                [Op.lt]: time
            }
        })

        const { count, rows } = await Activity.findAndCountAll(
            {
                where: whereOpt,
                order: [
                    // 将转义 title 并针对有效方向列表进行降序排列
                    ['createdAt', 'DESC'],
                ],
                offset: offect * 1,
                limit: limit * 1,
            },
        )
        return { count, rows }
    }

    /**
     * 按活动id寻找活动详细信息
     */
    async getACtDetailById (act_id) {
        try {
            const res = await Activity.findOne({ where: { act_id } })
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }

    /**
     * 修改活动信息
     */
    async modifyByActId (modifyData, act_id) {
        try {
            const res = await Activity.update(modifyData, { where: { act_id } })
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }
}

module.exports = new ActivityService()